﻿using System;
using System.Drawing;
using System.Web;
using System.Web.Mvc;
using GdHotel.Data.Helpers;
using GdHotel.Data.Interfaces;
using GdHotel.Data.Resources;
using UniqueTechnologies.Attributes;
using UniqueTechnologies.Data.Interfaces;

namespace GdHotel.Web.Controllers
{
    [LanguageSupport]
    [Authorize(Roles = "Admin")]
    public class ManageImagesController : BaseController
    {
        public IImagesRepository ImagesRepository { get; set; }
        public override ILanguagesRepository LanguagesRepository { get; set; }

        public ManageImagesController(IImagesRepository imagesRepository, ILanguagesRepository languagesRepository)
        {
            ImagesRepository = imagesRepository;
            LanguagesRepository = languagesRepository;
        }

        //
        // GET: /Images/

        public ActionResult Index(String message)
        {
            if (!String.IsNullOrEmpty(message) && message.Equals("fail"))
                ViewBag.Message = "Не удалось загрузить изображение";

            ImagesRepository.DirectoryName = HttpContext.Server.MapPath(Common.ImagesDirectory);
            ImagesRepository.RelativePathPrefix = "/UserContent/Images/";
            var models = ImagesRepository.FindAll();
            return View(models);
        }

        [HttpPost]
        public ActionResult Load(HttpPostedFileBase file, Int32? cropToWidth, Int32? cropToHeight)
        {
            if (file == null || file.ContentLength == 0)
                return RedirectToAction("Index", new {message = "fail"});

            if (cropToHeight.HasValue && cropToWidth.HasValue)
            {
                var pictureSize = new Size(cropToWidth.Value, cropToHeight.Value);
                GraphicsHelper.SaveAndResizePicture(file, pictureSize, Server, Common.ImagesDirectory);
            }
            else
            {
                file.SavePhoto(Common.ImagesDirectory, Server);
            }
            return RedirectToAction("Index");
        }
    }
}
